package com.probox.common.entity.service.product.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.probox.common.core.constant.CachePrefix;
import com.probox.common.core.enums.*;
import com.probox.common.core.exception.BaseException;
import com.probox.common.core.exception.ProductException;
import com.probox.common.core.utils.DateUtils;
import com.probox.common.entity.domain.order.OrderInfoItem;
import com.probox.common.entity.mapper.product.ProductUnitMapper;
import com.probox.common.entity.service.customer.ICustomerHiddenLabelService;
import com.probox.common.core.text.Convert;
import com.probox.common.core.utils.SecurityUtils;
import com.probox.common.core.utils.StringUtils;
import com.probox.common.core.utils.WechatQrCode.WeixinQrCodeUtil;
import com.probox.common.core.utils.money.MoneyUtils;
import com.probox.common.entity.domain.product.*;
import com.probox.common.entity.domain.product.vo.*;
import com.probox.common.entity.mapper.product.ProductInfoMapper;
import com.probox.common.entity.service.customer.ICustomerCollectService;
import com.probox.common.entity.service.customer.ICustomerLevelService;
import com.probox.common.entity.service.order.IOrderInfoItemService;
import com.probox.common.entity.service.platfom.IPlatformAddressService;
import com.probox.common.entity.service.platfom.IPlatformGeneralsettingsService;
import com.probox.common.entity.service.product.*;
import com.probox.common.entity.service.wechat.IWchatBroadcastService;
import com.probox.common.entity.service.wechat.WechatMiniService;
import com.probox.common.redis.service.RedisService;
import com.probox.customer.api.domain.CustomerCollect;
import com.probox.order.api.domain.OrderQuery;
import com.probox.product.api.domain.*;
import com.probox.wechat.api.domain.WxQrCode;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;


/**
 * 商品信息Service业务层处理
 *
 * @date 2021-05-28
 */
@Service
@Transactional
public class ProductInfoServiceImpl extends ServiceImpl<ProductInfoMapper, ProductInfo> implements IProductInfoService {

    @Autowired
    private ProductInfoMapper productInfoMapper;

    @Autowired
    private IProductInfoTagsService iProductInfoTagsService;

    @Autowired
    private IProductPropertyValuesService iProductPropertyValuesService;


    @Autowired
    private IProductBrandService iProductBrandService;

    @Autowired
    private IProductUnitService iProductUnitService;

    @Autowired
    private IProductCategoryService iProductCategoryService;

    @Autowired
    private IProductTagsService iProductTagsService;

    @Autowired
    private IProductSkuService iProductSkuService;

    @Autowired
    private IProductLogService iProductLogService;

    @Autowired
    private IProductCommentService iProductCommentService;

    @Autowired
    private IProductInfoGroupService iProductInfoGroupService;

    @Autowired
    private IProductGroupService iProductGroupService;


    @Autowired
    private RedisService redisService;

    @Autowired
    private ICustomerCollectService customerCollectService;

    @Autowired
    private IOrderInfoItemService orderInfoItemService;

    @Autowired
    private ProductUnitMapper productUnitMapper;




    @Override
    public ProductInfo getPro(Long productUid) {
        return this.getById(productUid);
    }


    private final String SIMG = "?imageslim"; // 图片瘦身

    final String ZERO = "0";//用于判断是否是商品列表
    final String NEGATIVEONE = "-1";//用于其他列表

    /**
     * 获得小程序二维码
     *
     * @param productUid
     * @return
     */
    @Override
    public String getAppltImg(Long productUid, Long platformUid) {

        return null;
    }

    /**
     * 获取h5的二维码
     *
     * @param productUid
     */
    @Override
    public HashMap getH5(Long productUid) {
        String url = "https://console.yooruan.com/h5/pages/productDetail/productDetail?id=" + productUid;
        HashMap map = new HashMap();

        return map;
    }


    //转换为图片流
    private static BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }
        return image;
    }

    /**
     * 查询是否被单位引用
     *
     * @param unitUid
     * @return
     */
    @Override
    public Boolean productUnitUse(Long unitUid) {
        QueryWrapper<ProductInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("UNIT_UID", unitUid);
        queryWrapper.ne("DATA_STATUS", DataStatus.delete.getKey());
        Integer integer = productInfoMapper.selectCount(queryWrapper);
        if (integer > 0) return true;
        else return false;
    }

    /**
     * 是否使用
     *
     * @param info
     * @return
     */
    @Override
    public Boolean useProduct(ProductInfo info) {
        return false;
    }

    @Override
    public LunWenVo getLunWenView(Long productUid){
        String key = CachePrefix.API_PRODUCT_DETAIL + productUid;
        ProductInfoVo infoVo = redisService.get(key, ProductInfoVo.class);
        Long userId = 0L;
        if (ObjectUtil.isNotEmpty(SecurityUtils.getCustomerUid())) {
            userId = SecurityUtils.getCustomerUid();
        }

        LunWenVo rst = new LunWenVo();
        ProductInfoVo vo = productInfoMapper.selectProduct(productUid);
        if (vo != null){
            BeanUtils.copyProperties(vo,rst);
            rst.setIsBuy("0");
            rst.setIsCollect("0");
            rst.setCreateDate(DateUtils.formate(vo.getCreateTime(),"yyyy-MM-dd"));
            rst.setShowDownloadBtn(true);
            rst.setShowMaiDuanBtn(true);
            //如果被买断了，需要验证当前的会员是否购买了论文
            if(vo.getBuyCount()>0){
                rst.setShowMaiDuanBtn(false);
                rst.setShowDownloadBtn(false);
            }
            //如果积分大于0说明是付费积分，貌似取消了
            if (vo.getJifen() > 0) {
                rst.setLowestJiFen(1);
            }

            if (StringUtils.isNotEmpty(vo.getDownloadFile())){
                rst.setFileExt(vo.getDownloadFile().substring(vo.getDownloadFile().lastIndexOf(".")+1));
            }else if (StringUtils.isNotEmpty(vo.getShowFile())){
                rst.setFileExt(vo.getShowFile().substring(vo.getShowFile().lastIndexOf(".")+1));
            }

            if (userId != null && userId>0L){
                CustomerCollect collect = new CustomerCollect();
                collect.setObjUid(vo.getProductUid());
                collect.setCustomerUid(userId);
                rst.setIsCollect(customerCollectService.getIsCollectGoods(collect)?"1":"0");

                OrderQuery query = new OrderQuery();
                query.setCustomerUid(userId);
                query.setProUid(vo.getProductUid());
                List<OrderInfoItem> buys = orderInfoItemService.selectLuwenOrderList(query);
                rst.setIsBuy(buys.size()>0?"1":"0");
                if (rst.getIsBuy().equals("1") && StringUtils.isNotEmpty(vo.getDownloadFile())){
                    rst.setShowFile(vo.getDownloadFile());
                }
                //如果被人买了，自己却没有买那么是不能下载的
                if (buys.size()==0 && !rst.getShowMaiDuanBtn()){
                    rst.setShowDownloadBtn(false);
                }else {
                    rst.setShowDownloadBtn(true);
                }
            }
        }else{
            if (ObjectUtil.isEmpty(vo)) throw new ProductException("没有找到论文资料！");
        }
        if (!rst.getShowMaiDuanBtn() && !rst.getShowDownloadBtn() ){
            throw new ProductException("该论文不支持预览！");
        }
        if (StringUtils.isNotEmpty(rst.getShowFile()) && rst.getShowFile().startsWith("http:")){
            rst.setShowFile("https:"+rst.getShowFile().substring(5));
        }
        try {
            rst.setShowFile(URLEncoder.encode("https://vw.usdoc.cn/?m=1&src=" + rst.getShowFile(), "utf-8"));
        }catch (Exception e){
            rst.setShowFile("https://vw.usdoc.cn/?m=1&src=" + rst.getShowFile());
        }
        rst.setJifen(getDownloadJiFen(rst));
        return rst;
    }

    /**
     * api获得商品详情信息
     *
     * @param productUid
     * @return
     */
    @Override
    public ProductInfoVo getProductView(Long productUid) {
        String key = CachePrefix.API_PRODUCT_DETAIL + productUid;
        ProductInfoVo infoVo = redisService.get(key, ProductInfoVo.class);
        Long userId = 0L;
        if (ObjectUtil.isNotEmpty(SecurityUtils.getCustomerUid())) {
            userId = SecurityUtils.getCustomerUid();
        }
        ProductInfo byId = new ProductInfo();
        if (ObjectUtil.isEmpty(infoVo)) {
            infoVo = new ProductInfoVo();
            QueryWrapper<ProductInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("PRODUCT_UID", productUid);
            queryWrapper.eq("PLATFORM_UID", SecurityUtils.getCustomerPlatformUid());
            byId = productInfoMapper.selectOne(queryWrapper);
            if (ObjectUtil.isEmpty(byId)) throw new ProductException("商品不存在！");
            if (!DataStatus.valid.getKey().equals(byId.getDataStatus())) {
                throw new ProductException("该商品已下架！");
            }
            BeanUtils.copyProperties(byId, infoVo);
            // 查询销量
            //ProductCount productCount = iProductCountService.selectProductCountByProId(productUid);
            //if (ObjectUtil.isNotEmpty(productCount)) infoVo.setBuyNum(productCount.getBuyNum());
            //查询商品标签
            infoVo.setTagsName(iProductTagsService.getTagsName(productUid));
            // 商品单位
            ProductUnit productUnit = null;
            if (ObjectUtil.isNotEmpty(infoVo.getUnitUid()))
                productUnit = iProductUnitService.selectProductUnitById(infoVo.getUnitUid());
            if (ObjectUtil.isNotEmpty(productUnit)) infoVo.setUnitName(productUnit.getUnitName());
            // 查询商品评论
            ProductCommentQuery productCommentQuery = new ProductCommentQuery();
            productCommentQuery.setProductUid(productUid);
            productCommentQuery.setPlatformUid(SecurityUtils.getCustomerPlatformUid());
            PageHelper.startPage(1, 3);
            List<ProductCommentVo> productCommentVos = iProductCommentService.queryList(productCommentQuery);
            List<ProductCommentApiVo> list = new ArrayList<>();
            if (ObjectUtil.isNotEmpty(productCommentVos)) {
                productCommentVos.forEach(vo -> {
                    ProductCommentApiVo productCommentApiVo = new ProductCommentApiVo();
                    BeanUtils.copyProperties(vo, productCommentApiVo);
                    list.add(productCommentApiVo);
                });
                infoVo.setProductCommentList(list);
                infoVo.setCommentCount(list.size());
            }
            //查询商品属性
            infoVo = setProertyList(infoVo);
            infoVo.setBrand(iProductBrandService.getBrandVo(infoVo.getBrandUid()));
            List<HashMap> productProerytyVo = infoVo.getProductProerytyVo();
            if (ObjectUtil.isEmpty(productProerytyVo)) {
                productProerytyVo = new ArrayList<>();
            }
            if (ObjectUtil.isNotEmpty(infoVo.getProductPlaceProvinceName())) {
                productProerytyVo = setList("省份", infoVo.getProductPlaceProvinceName(), productProerytyVo);
            }
            if (ObjectUtil.isNotEmpty(infoVo.getProductPlaceCityName())) {
                productProerytyVo = setList("城市", infoVo.getProductPlaceCityName(), productProerytyVo);
            }
            if (ObjectUtil.isNotEmpty(infoVo.getProductPlaceAreaName())) {
                productProerytyVo = setList("区县", infoVo.getProductPlaceAreaName(), productProerytyVo);
            }
            if (ObjectUtil.isNotEmpty(infoVo.getBrand())) {
                productProerytyVo = setList("品牌", infoVo.getBrand().getBrandName(), productProerytyVo);
            }

            // 瘦身图片
            StringBuffer stringBufferCarouse = new StringBuffer();
            String carouselImg = infoVo.getCarouselImg();
            String[] splitCarouse = carouselImg.split(",");
            for (int i = 0; i < splitCarouse.length; i++) {
                if (0 > splitCarouse[i].indexOf(SIMG)) {
                    splitCarouse[i] = splitCarouse[i] + SIMG;
                }
                stringBufferCarouse.append("," + splitCarouse[i]);
            }
            infoVo.setCarouselImg(stringBufferCarouse.toString());
            infoVo.setCarouselImg(infoVo.getCarouselImg().substring(1, infoVo.getCarouselImg().length()));
            StringBuffer stringBufferDetail = new StringBuffer();
            String detailImg = infoVo.getDetailImg();
            String[] splitDetail = detailImg.split(",");
            for (int i = 0; i < splitDetail.length; i++) {
                if (0 > splitDetail[i].indexOf(SIMG)) {
                    splitDetail[i] = splitDetail[i] + SIMG;
                }
                stringBufferDetail.append("," + splitDetail[i]);
            }
            infoVo.setDetailImg(stringBufferDetail.toString());
            infoVo.setDetailImg(infoVo.getDetailImg().substring(1, infoVo.getDetailImg().length()));
            if (ObjectUtil.isEmpty(infoVo.getShareImg())) infoVo.setShareImg(infoVo.getcarouselImgOne());
            if (0 > infoVo.getShareImg().indexOf(SIMG)) {
                infoVo.setShareImg(infoVo.getShareImg() + SIMG);
            }
            if (StringUtils.isNotEmpty(infoVo.getShareImg())) {
                String shareImg = infoVo.getShareImg();
                if (!shareImg.startsWith("https")) {
                    infoVo.setShareImg(shareImg.replace("http", "https"));
                }
            }

            infoVo.setProductProerytyVo(productProerytyVo);
            redisService.set(key, infoVo, 5L, TimeUnit.MINUTES);
        }

        infoVo.setStockNumber(getStockNum(productUid));


        return infoVo;
    }

    private Long getStockNum(Long uid) {

        return 0L;
    }

    /**
     * 商品详情的远程调用
     *
     * @param infoVo
     * @param userId
     * @param SupplierUid
     * @return
     */
    private ProductInfoVo fegin(ProductInfoVo infoVo, Long userId, Long SupplierUid) {
        return null;
    }

    /**
     * 商品属性
     *
     * @param infoVo
     * @return
     */
    public ProductInfoVo setProertyList(ProductInfoVo infoVo) {
        List<ProductProerytyVo> productProerytyVos = iProductPropertyValuesService.queryValuesName(infoVo.getProductUid());
        if (ObjectUtil.isNotEmpty(productProerytyVos)) {
            List<HashMap> list = new ArrayList<>();
            String chandi = "";
            for (ProductProerytyVo vo : productProerytyVos) {
                if (vo.getSpecsName().equals("产地")) {
                    chandi = vo.getValuesName();
                    continue;
                }
                HashMap map = new HashMap();
                map.put("name", vo.getSpecsName());
                map.put("value", vo.getValuesName());
                list.add(map);
            }
            if (!"".equals(chandi)) {
                HashMap map = new HashMap();
                map.put("name", "产地");
                map.put("value", chandi);
                list.add(map);
            }
            infoVo.setProductProerytyVo(list);
        }
        return infoVo;
    }

    /**
     * 产品销售，需要修改商品库存和SKU的库存，并更新商品的销量
     *
     * @param vo
     */
    @Override
    public void saleProduct(SaleProductVo vo) {
        if (vo.getProductId() != null && vo.getNumber() > 0) {
            this.productInfoMapper.updateProductStock(vo);
            //iProductCountService.incrSaleNum(vo.getProductId(), Long.valueOf(vo.getNumber()), null);
        }
        if (vo.getSkuId() != null) {
            iProductSkuService.saleSku(vo);
        }

        redisService.deleteObject(CachePrefix.PRODUCT_STOCK_NUMBER + vo.getProductId());
        redisService.deleteObject(CachePrefix.API_PRODUCT_DETAIL + vo.getProductId());
    }

    @Override
    public int incProductDownloadCount(Long productUid) {
        return productInfoMapper.incProductDownloadCount(productUid);
    }

    @Override
    public int incProductBuyCount(Long productUid) {
        return productInfoMapper.incProductBuyCount(productUid);
    }

    /**
     * api获取商品sku的详细信息
     *
     * @param productUid
     * @return
     */
    @Override
    public ProductSkuVo getProductSkuVo(Long productUid) {


        return null;
    }


    /**
     * 查询商品信息列表
     *
     * @param productInfoQuery 商品信息
     * @return 商品信息
     */
    @Override
    public List<ProductInfoVo> queryList(ProductInfoQuery productInfoQuery) {
        Long platformId = SecurityUtils.getPlatformId();
        if (platformId == null) {
            throw new BaseException("当前账号异常");
        }
        productInfoQuery.setPlatformUid(platformId);
        Long supplierId = SecurityUtils.getSupplierId();
        if (supplierId != 0L) {
            productInfoQuery.setSupplierUid(supplierId);
        }
        if (ObjectUtil.isNotEmpty(productInfoQuery.getTagsUid())) {
            productInfoQuery.setTagsProUid(iProductInfoTagsService.getProductTags(productInfoQuery));
        }
        //productInfoQuery.setSortProperty("1");

        List<ProductInfoVo> productInfoVos = productInfoMapper.selectProductList(productInfoQuery);

        if (ObjectUtil.isEmpty(productInfoVos)) return productInfoVos;
        List<ProductCategory> categories = iProductCategoryService.queryList(new ProductCategory());
        Map<Long,String> cateMap = new HashMap<>();
        for (ProductCategory c:categories) {
            cateMap.put(c.getCategoryUid(),c.getCategoryName());
        }
        List<ProductInfoVo> list = new ArrayList<>();
        productInfoVos.forEach(info -> {
            ProductInfoVo vo = new ProductInfoVo();
            BeanUtils.copyProperties(info, vo);
            if(vo.getMajorUidOne() != null){
                vo.setMajorUidOneName(cateMap.get(vo.getMajorUidOne()));
            }
            if(vo.getMajorUidTwo() != null){
                vo.setMajorUidTwoName(cateMap.get(vo.getMajorUidTwo()));
            }
            if(vo.getMajorUidThree() != null){
                vo.setMajorUidThreeName(cateMap.get(vo.getMajorUidThree()));
            }
            if (vo.getCategoryUid() != null){
                ProductGroup pc= iProductGroupService.getById(vo.getCategoryUid());
                if (pc != null) {
                    vo.setCategoryName(pc.getGroupName());
                }
            }
            list.add(vo);
        });
        return list;
    }


    /**
     * 前端获取商品信息列表
     *
     * @param lunWenVo
     * @return
     */
    @Override
    public List<LunWenVo> select(LunWenVo lunWenVo) {
        return productInfoMapper.selectLunWenList(lunWenVo);
    }

    @Override
    public int getDownloadJiFen(LunWenVo lunWenVo) {
        int jifen = lunWenVo.getJifen();
        if (lunWenVo.getDownloadCount()==0 || jifen==0){
            return jifen;
        }
        QueryWrapper<ProductUnit> wrapper = new QueryWrapper<>();
        wrapper.eq("group_uid",lunWenVo.getCategoryUid());
        wrapper.ge("START_COUNT",lunWenVo.getDownloadCount());
        wrapper.le("END_COUNT",lunWenVo.getDownloadCount());
        wrapper.eq("DATA_STATUS",DataStatus.valid.getKey());
        wrapper.orderByAsc("DATA_PRIORITY");
        wrapper.last(" limit 1");
        List<ProductUnit> list = productUnitMapper.selectList(wrapper);
        if (list.size()==0){
            return jifen;
        }
        jifen = list.get(0).getDiscount().multiply(new BigDecimal(jifen)).intValue();
        return jifen;
    }

    /**
     * 前端获取商品信息列表
     *
     * @param lunWenVo
     * @returns
     */
    @Override
    public Integer selectCount(LunWenVo lunWenVo) {
        return productInfoMapper.selectLunWenCount(lunWenVo);
    }

    @Override
    public Integer selectCountAdmin(ProductInfoQuery productInfoQuery) {
        return productInfoMapper.selectCountAdmin(productInfoQuery);
    }

    /**
     * 查询猜你喜欢的商品
     *
     * @param productInfoQuery
     * @return
     */
    @Override
    public List<ProductInfoVo> selectLike(ProductInfoQuery productInfoQuery) {
        return new ArrayList<>();
    }


    /**
     * 新增所有关于商品的
     *
     * @param productSaveVo 商品信息
     * @param one           是否一键上架
     * @return 结果
     */
    @Override
    public boolean insertProductInfo(ProductSaveVo productSaveVo, Long one) {
        if (ObjectUtil.isNotNull(productSaveVo)) {
            productSaveVo.setPlatformUid(SecurityUtils.getPlatformId());
            productSaveVo.setUserName(SecurityUtils.getUsername());
            productSaveVo.setUserUid(SecurityUtils.getUserId());
            productSaveVo.setTime(DateUtil.date());

            productSaveVo.setHaveSku("0");

            ProductInfo productInfo = saveInfo(productSaveVo);// 添加商品
            productSaveVo.setProductUid(productInfo.getProductUid());
            iProductInfoTagsService.insertProductInfoTags(productSaveVo);// 添加标签中间关系表

            if (one == 1L) {
                getGrounding(productInfo.getProductUid());
                redisService.deleteObject(CachePrefix.PRODUCT_CATEGORY_TWO_BANNER + productInfo.getMajorUidOne());
            }
            if (one == 2L) {//保存并提交
                iProductLogService.insertProductsLog(new ProductLog(productInfo.getProductUid(), null, ProductLogType.submit.getKey(), "", productSaveVo.getTime()));
                productInfo.setAuditStatus(ProductAuditStatus.toAudit.getKey());
                this.updateById(productInfo);
            }
        }

        return true;
    }

    /**
     * 修改商品信息
     *
     * @param productSaveVo 商品信息
     * @return 结果
     */
    @Override
    public boolean updateProductInfo(ProductSaveVo productSaveVo, Long one) {
        productSaveVo.setPlatformUid(SecurityUtils.getPlatformId());
        productSaveVo.setUserName(SecurityUtils.getUsername());
        productSaveVo.setUserUid(SecurityUtils.getUserId());
        productSaveVo.setTime(DateUtil.date());

        ProductInfo productInfo = editInfo(productSaveVo);//修改商品信息


            iProductLogService.insertProductsLog(new ProductLog(productInfo.getProductUid(), null, ProductLogType.submit.getKey(), "", productSaveVo.getTime()));
            productInfo.setAuditStatus(ProductAuditStatus.toAudit.getKey());
            this.updateById(productInfo);


        iProductInfoTagsService.updateProductInfoTags(productSaveVo);// 修改标签中间表

        //删除前端缓存
        redisService.deleteObject(CachePrefix.API_PRODUCT_DETAIL + productInfo.getProductUid());
        redisService.deleteObject(CachePrefix.TEMPLATE_PRODUCT + productInfo.getProductUid());
        redisService.deleteObject(CachePrefix.PRODUCT_STOCK_NUMBER + productInfo.getProductUid());

        iProductInfoGroupService.delRedisGroup(productInfo.getProductUid());
        return true;
    }

    /**
     * 批量删除商品信息
     *
     * @param productUids 需要删除的商品信息ID
     * @return 结果
     */
    @Override
    public boolean deleteProductInfoByIds(Long[] productUids) {
        ProductSaveVo productSaveVo = new ProductSaveVo();
        productSaveVo.setPlatformUid(SecurityUtils.getPlatformId());
        productSaveVo.setUserName(SecurityUtils.getUsername());
        productSaveVo.setUserUid(SecurityUtils.getUserId());
        productSaveVo.setTime(DateUtil.date());
        UpdateWrapper<ProductInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("DATA_STATUS", DataStatus.delete.getKey());
        updateWrapper.set("UPDATE_UID", productSaveVo.getUserUid());
        updateWrapper.set("UPDATE_NAME", productSaveVo.getUserName());
        updateWrapper.set("UPDATE_TIME", productSaveVo.getTime());
        updateWrapper.in("PRODUCT_UID", productUids);
        boolean update = this.update(updateWrapper);
        if (!update) throw new ProductException("修改失败,请稍后再试!");
        iProductPropertyValuesService.editProductSkuValues(productSaveVo, productUids); // 删除中间数据
        iProductSkuService.updateSkuStatus(productSaveVo, productUids); // 删除sku
        iProductInfoTagsService.updateInfoTagStatus(productUids);
        return true;
    }


    /**
     * 添加商品信息表
     *
     * @param productSaveVo 商品信息 vo
     * @return
     */
    private ProductInfo saveInfo(ProductSaveVo productSaveVo) {
        Long userId = productSaveVo.getUserUid();
        String username = productSaveVo.getUserName();
        Date date = productSaveVo.getTime();
        ProductInfo productInfo = new ProductInfo();
        BeanUtils.copyProperties(productSaveVo, productInfo);

        productInfo.setDataStatus(DataStatus.valid.getKey());
        //productInfo.setPlatformUid(productSaveVo.getPlatformUid());
        productInfo.setCreateUid(userId);
        productInfo.setCreateName(username);
        productInfo.setCreateTime(date);
        productInfo.setUpdateUid(userId);
        productInfo.setUpdateName(username);
        productInfo.setUpdateTime(date);
        productInfo.setDataPriority(1L);

        if (productSaveVo.getMajorUids().length == 1) {
            productInfo.setMajorUidOne(productSaveVo.getMajorUids()[0]);
            productInfo.setMajorUidTwo(0l);
            productInfo.setMajorUidThree(0L);
        } else if (productSaveVo.getMajorUids().length == 2) {
            productInfo.setMajorUidOne(productSaveVo.getMajorUids()[0]);
            productInfo.setMajorUidTwo(productSaveVo.getMajorUids()[1]);
            productInfo.setMajorUidThree(0L);
        }else if (productSaveVo.getMajorUids().length == 3) {
            productInfo.setMajorUidOne(productSaveVo.getMajorUids()[0]);
            productInfo.setMajorUidTwo(productSaveVo.getMajorUids()[1]);
            productInfo.setMajorUidThree(3L);
        }



        productInfo.setAuditStatus(ProductAuditStatus.normal.getKey());
        productInfo.setSumbitStatus(ProductSumbitStatus.normal.getKey());


        boolean save = this.save(productInfo);
        if (!save) throw new ProductException("添加失败,请稍后再试!");
        return productInfo;
    }

    /**
     * 修改商品信息
     *
     * @param productSaveVo 商品信息 vo
     * @return
     */
    private ProductInfo editInfo(ProductSaveVo productSaveVo) {
        ProductInfo productInfo = new ProductInfo();
        BeanUtils.copyProperties(productSaveVo, productInfo);


        if (productSaveVo.getMajorUids().length == 1) {
            productInfo.setMajorUidOne(productSaveVo.getMajorUids()[0]);
            productInfo.setMajorUidTwo(0l);
            productInfo.setMajorUidThree(0L);
        } else if (productSaveVo.getMajorUids().length == 2) {
            productInfo.setMajorUidOne(productSaveVo.getMajorUids()[0]);
            productInfo.setMajorUidTwo(productSaveVo.getMajorUids()[1]);
            productInfo.setMajorUidThree(0L);
        }else if (productSaveVo.getMajorUids().length == 3) {
            productInfo.setMajorUidOne(productSaveVo.getMajorUids()[0]);
            productInfo.setMajorUidTwo(productSaveVo.getMajorUids()[1]);
            productInfo.setMajorUidThree(3L);
        }
        productInfo.setUpdateUid(productSaveVo.getUserUid());
        productInfo.setUpdateName(productSaveVo.getUserName());
        productInfo.setUpdateTime(productSaveVo.getTime());

        boolean b = this.updateById(productInfo);
        if (!b) throw new ProductException("修改失败,请稍后再试！");
        return productInfo;
    }

    /**
     * 获得商品详细的vo
     *
     * @param productUid
     * @return
     */
    @Override
    public ProductSaveVo getSaveVo(Long productUid) {
        ProductSaveVo productSaveVo = new ProductSaveVo();
        ProductInfo productInfo = this.getById(productUid);
        if (ObjectUtil.isNotNull(productInfo)) {
            BeanUtils.copyProperties(productInfo, productSaveVo);

            int index = 0;
            if (ObjectUtil.isNotEmpty(productInfo.getMajorUidOne()) && productInfo.getMajorUidOne()!=0) index++;
            if (ObjectUtil.isNotEmpty(productInfo.getMajorUidTwo()) && productInfo.getMajorUidTwo()!=0) index++;
            if (ObjectUtil.isNotEmpty(productInfo.getMajorUidThree()) && productInfo.getMajorUidThree()!=0) index++;
            Long[] categoryUid = new Long[index];
            if (index > 0) categoryUid[0] = productInfo.getMajorUidOne();
            if (index > 1) categoryUid[1] = productInfo.getMajorUidTwo();
            if (index > 2) categoryUid[2] = productInfo.getMajorUidThree();
            productSaveVo.setMajorUids(categoryUid);
            productSaveVo.setTagsUid(iProductInfoTagsService.selectProductInfoTagsArray(productUid));
            productSaveVo.setIsTraditionDuplicate(productInfo.getIsTraditionDuplicate());
            productSaveVo.setIsAigcDuplicate(productInfo.getIsAigcDuplicate());
            productSaveVo.setCostPrice(productInfo.getCostPrice());
            productSaveVo.setShowFile(httpToHttps(productSaveVo.getShowFile()));
            productSaveVo.setDownloadFile(httpToHttps(productSaveVo.getDownloadFile()));
        }
        return productSaveVo;
    }

    private String httpToHttps(String file){
        String rst = "https:";
        if (StringUtils.isNotEmpty(file) && file.startsWith("http:")){
            rst += file.substring(5);
        }else {
            rst = file;
        }
        return rst;
    }

    /**
     * 查询商品详情的页面
     *
     * @param productUid
     * @return
     */
    @Override
    public ProductViewVo getViewVo(Long productUid) {
        ProductViewVo productViewVo = new ProductViewVo();
        ProductInfo productInfo = productInfoMapper.selectById(productUid);
        if (ObjectUtil.isNotEmpty(productInfo)) {
            BeanUtils.copyProperties(productInfo, productViewVo);

            productViewVo.setCategoryName(iProductCategoryService.getCategoryName(productInfo));
            productViewVo.setList(iProductPropertyValuesService.queryValuesName(productUid));

            productViewVo.setCostPrice(productInfo.getCostPrice());

            productViewVo.setTags(iProductTagsService.getTagsName(productUid));

            List<ProductSku> productSkus = iProductSkuService.queryList(productUid);
            if (ObjectUtil.isNotEmpty(productSkus)) {
                List<SkuSaveVo> skuSaveVoList = iProductSkuService.getSkuSaveVoList(productSkus);
                productViewVo.setSkuSaveVo(skuSaveVoList);
                productViewVo.setIsSku(true);
            } else productViewVo.setIsSku(false);

        }
        return productViewVo;
    }

    /**
     * 通过uid集查询商品信息
     *
     * @param uids 商品id集
     * @return
     */
    @Override
    public List<ProductInfoVo> getProductList(String uids) {
        List<ProductInfoVo> list = new ArrayList<>();
        String[] split = uids.split(",");
        Long[] arr = new Long[split.length];
        for (int i = 0; i < split.length; i++) {
            arr[i] = Convert.toLong(split[i]);
        }
        QueryWrapper<ProductInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("PRODUCT_UID", arr);
        queryWrapper.ne("DATA_STATUS", DataStatus.delete.getKey());
        List<ProductInfo> productInfos = productInfoMapper.selectList(queryWrapper);
        if (ObjectUtil.isNotEmpty(productInfos)) {
            productInfos.forEach(info -> {
                ProductInfoVo productInfoVo = new ProductInfoVo();
                BeanUtils.copyProperties(info, productInfoVo);
                list.add(productInfoVo);
            });
        }
        return list;
    }

    /**
     * 查询修改库存的数据
     *
     * @param productUid
     * @return
     */
    @Override
    public List<ProductEditVo> queryEditVo(Long productUid) {
        List<ProductEditVo> list = null;
        list = productInfoMapper.queryEditVo(productUid);
        if (ObjectUtil.isEmpty(list)) {
            ProductInfo byId = this.getById(productUid);
            ProductEditVo productEditVo = new ProductEditVo();
            BeanUtils.copyProperties(byId, productEditVo);
            list.add(productEditVo);
        }
        return list;
    }

    /**
     * 用于修改库存和修改价格
     *
     * @param vol
     * @return
     */
    @Override
    public Boolean updateEdit(ProductEditAllVo vol) {
        List<ProductEditVo> list = vol.getList();
        if (ObjectUtil.isEmpty(list)) return true;
        String type = vol.getType();//1修改价格 其余是修改库存
        Date time = DateUtil.date();
        Long userId = SecurityUtils.getUserId();
        String name = SecurityUtils.getUsername();
        AtomicReference<Integer> index = new AtomicReference<>(0);// 用于最后是否修改整体的商品库存
        AtomicReference<Long> count = new AtomicReference<>(0L);// 商品总库存
        AtomicReference<BigDecimal> skuCos = new AtomicReference<>(BigDecimal.ZERO);//取sku的价格
        AtomicReference<BigDecimal> skuRet = new AtomicReference<>(BigDecimal.ZERO);//取sku的价格
        AtomicReference<BigDecimal> skuPri = new AtomicReference<>(BigDecimal.ZERO);//取sku的价格
        if (ObjectUtil.isNotEmpty(list)) {
            list.forEach(vo -> {
                if (ObjectUtil.isEmpty(vo.getSkuUid())) {
                    index.set(0);
                    ProductInfo productInfo = this.getById(vo.getProductUid());
                    if (ObjectUtil.isNotEmpty(productInfo)) {

                        if ("1".equals(type)) {
                            revisePrice(productInfo, null, vo, time);
                        }
                        BeanUtils.copyProperties(vo, productInfo);

                        if ("1".equals(type)) {

                            productInfo.setCostPrice(vo.getCostPrice());

                        }
                        productInfo.setUpdateUid(userId);
                        productInfo.setUpdateName(name);
                        productInfo.setUpdateTime(time);
                        this.updateById(productInfo);
                        //删除前端缓存
                        redisService.deleteObject(CachePrefix.API_PRODUCT_DETAIL + productInfo.getProductUid());
                        redisService.deleteObject(CachePrefix.TEMPLATE_PRODUCT + productInfo.getProductUid());
                        redisService.deleteObject(CachePrefix.PRODUCT_STOCK_NUMBER + productInfo.getProductUid());
                        iProductInfoGroupService.delRedisGroup(productInfo.getProductUid());
                    } else throw new ProductException("商品数据有问题,请刷新页面!");
                } else {

                    ProductSku productSku = iProductSkuService.selectProductsSkuById(vo.getSkuUid());
                    if (ObjectUtil.isNotEmpty(productSku)) {
                        Long stockNumber = productSku.getStockNumber();
                        if ("1".equals(type)) {
                            revisePrice(null, productSku, vo, time);
                        }
                        BeanUtils.copyProperties(vo, productSku);
                        if ("1".equals(type)) {
                            productSku.setCostPrice(MoneyUtils.changeY2B(vo.getSkuCostPrice()));
                            productSku.setSkuRetailPrice(MoneyUtils.changeY2B(vo.getSkuRetailPrice()));
                            productSku.setSkuTradePrice(MoneyUtils.changeY2B(vo.getSkuTradePrice()));
                            if (index.get() == 0) {
                                skuCos.set(productSku.getCostPrice());
                                skuPri.set(productSku.getSkuTradePrice());
                                skuRet.set(productSku.getSkuRetailPrice());
                            }
                        }
                        productSku.setStockNumber(vo.getSkuStockNumber());
                        Long stockNumberAdd = productSku.getStockNumber();
                        if (stockNumber != stockNumberAdd) {
                            iProductLogService.insertProductsLog(new ProductLog(vo.getProductUid(), vo.getSkuUid(), ProductLogType.modifyInventory.getKey(), "商品库存由" + stockNumber + "改为" + stockNumberAdd, time));
                        }
                        iProductSkuService.updateProductsSku(productSku);
                        count.updateAndGet(v -> v + stockNumberAdd);
                        index.set(1);
                    } else throw new ProductException("商品数据有问题,请刷新页面!");
                }
            });
            if (index.get() == 1) {
                ProductInfo info = this.getById(list.get(0).getProductUid());


            }
        }

        return true;
    }


    /**
     * 商品修改价格
     *
     * @param productInfo
     * @param productSku
     * @param productEditVo
     * @param time
     */
    private void revisePrice(ProductInfo productInfo, ProductSku productSku, ProductEditVo productEditVo, Date time) {
        if (ObjectUtil.isEmpty(productSku)) {



        } else {
            Long skuUid = productSku.getSkuUid();
            String costPrice = MoneyUtils.changeF2B(productSku.getCostPrice());
            String retailPrice = MoneyUtils.changeF2B(productSku.getSkuRetailPrice());
            String tradePrice = MoneyUtils.changeF2B(productSku.getSkuTradePrice());
            String costPriceNew = productEditVo.getSkuCostPrice().toString();
            String retailPriceNew = productEditVo.getSkuRetailPrice().toString();
            String tradePriceNew = productEditVo.getSkuTradePrice().toString();
            if (!costPrice.equals(costPriceNew)) {
                iProductLogService.insertProductsLog(new ProductLog(productEditVo.getProductUid(), skuUid, ProductLogType.revisePrice.getKey(), "供货价由" + costPrice + "改为" + costPriceNew, time));
            }
            if (!retailPrice.equals(retailPriceNew)) {
                iProductLogService.insertProductsLog(new ProductLog(productEditVo.getProductUid(), skuUid, ProductLogType.revisePrice.getKey(), "零售价由" + retailPrice + "改为" + retailPriceNew, time));
            }
            if (!tradePrice.equals(tradePriceNew)) {
                iProductLogService.insertProductsLog(new ProductLog(productEditVo.getProductUid(), skuUid, ProductLogType.revisePrice.getKey(), "批发价由" + tradePrice + "改为" + tradePriceNew, time));
            }
        }
    }

    /**
     * 商品一键上架
     *
     * @param productUid
     * @return
     */
    @Override
    public boolean getGrounding(Long productUid) {
        ProductInfo productInfo = this.getById(productUid);
        if (ObjectUtil.isEmpty(productInfo)) throw new ProductException("商品不存在！");
        if (DataStatus.delete.getKey().equals(productInfo.getDataStatus())) throw new ProductException("商品不存在！");
        Date time = DateUtil.date();
        Long userId = SecurityUtils.getUserId();
        String username = SecurityUtils.getUsername();
        productInfo.setDataStatus(DataStatus.valid.getKey());
        productInfo.setAuditStatus(ProductAuditStatus.pass.getKey());
        productInfo.setAuditUid(userId);
        productInfo.setAuditName(username);
        productInfo.setAuditTime(time);
        productInfo.setUpdateUid(userId);
        productInfo.setUpdateName(username);
        productInfo.setUpdateTime(time);
        productInfo.setSumbitStatus(ProductSumbitStatus.normal.getKey());
        productInfo.setSubmitUid(userId);
        productInfo.setSubmitName(username);
        productInfo.setSubmitTime(time);
        iProductLogService.insertProductsLog(new ProductLog(productInfo.getProductUid(), null, ProductLogType.dataStatus.getKey(), "该商品一键上架！", time));
        return this.updateById(productInfo);
    }

    /**
     * 用于审核,提交,上下架的操作以及日志的添加
     *
     * @param productInfoEditVo 商品信息Vo
     * @return
     */
    @Override
    public boolean editAndSaveLog(ProductInfoEditVo productInfoEditVo) {
        Date time = DateUtil.date();
        Long userId = SecurityUtils.getUserId();
        String username = SecurityUtils.getUsername();
        List<Long> productUidS = productInfoEditVo.getProductUids();
        if (ObjectUtil.isEmpty(productUidS)) throw new ProductException("数据有问题,请稍后再试！");
        productUidS.forEach(uid -> {
            ProductInfo productInfo = new ProductInfo();
            productInfo.setProductUid(uid);
            // 审核和申请
            if (ObjectUtil.isNotEmpty(productInfoEditVo.getAuditStatus()) || ObjectUtil.isNotEmpty(productInfoEditVo.getSumbitStatus())) {
                productInfo = this.getById(productInfo.getProductUid());
                if (ObjectUtil.isEmpty(productInfo)) throw new ProductException("商品信息错误,请刷新页面！");
                if (ProductAuditStatus.pass.getKey().equals(productInfoEditVo.getAuditStatus())) {
                    if (!ProductAuditStatus.toAudit.getKey().equals(productInfo.getAuditStatus()))
                        throw new ProductException("商品数据发生变化,请刷新页面！");
                    if (ObjectUtil.isEmpty(productInfoEditVo.getDetailInfo())) productInfoEditVo.setDetailInfo("");
                    iProductLogService.insertProductsLog(new ProductLog(productInfo.getProductUid(), null, ProductLogType.approved.getKey(), productInfoEditVo.getDetailInfo(), time));
                    productInfo.setAuditStatus(productInfoEditVo.getAuditStatus());
                    productInfo.setAuditUid(userId);
                    productInfo.setAuditName(username);
                    productInfo.setAuditTime(time);
                }
                if (ProductAuditStatus.reject.getKey().equals(productInfoEditVo.getAuditStatus())) {
                    if (!ProductAuditStatus.toAudit.getKey().equals(productInfo.getAuditStatus()))
                        throw new ProductException("商品数据发生变化,请刷新页面！");
                    iProductLogService.insertProductsLog(new ProductLog(productInfo.getProductUid(), null, ProductLogType.rejection.getKey(), productInfoEditVo.getDetailInfo(), time));
                    productInfo.setAuditStatus(productInfoEditVo.getAuditStatus());
                    productInfo.setAuditUid(userId);
                    productInfo.setAuditName(username);
                    productInfo.setAuditTime(time);
                }
                if (ProductAuditStatus.toAudit.getKey().equals(productInfoEditVo.getAuditStatus())) {
                    if (!ProductAuditStatus.reject.getKey().equals(productInfo.getAuditStatus()) && !ProductAuditStatus.normal.getKey().equals(productInfo.getAuditStatus()))
                        throw new ProductException("商品数据发生变化,请刷新页面！");
                    iProductLogService.insertProductsLog(new ProductLog(productInfo.getProductUid(), null, ProductLogType.submit.getKey(), productInfoEditVo.getDetailInfo(), time));
                    productInfo.setAuditStatus(productInfoEditVo.getAuditStatus());
                    productInfo.setAuditUid(userId);
                    productInfo.setAuditName(username);
                    productInfo.setAuditTime(time);
                }
                if (ProductSumbitStatus.applyForSale.getKey().equals(productInfoEditVo.getSumbitStatus())) {
                    iProductLogService.insertProductsLog(new ProductLog(productInfo.getProductUid(), null, ProductLogType.applyForListing.getKey(), "供应商申请上架商品", time));
                    productInfo.setSumbitStatus(productInfoEditVo.getSumbitStatus());
                    productInfo.setSubmitUid(userId);
                    productInfo.setSubmitName(username);
                    productInfo.setSubmitTime(time);
                }
                if (ProductSumbitStatus.applyForSold.getKey().equals(productInfoEditVo.getSumbitStatus())) {
                    iProductLogService.insertProductsLog(new ProductLog(productInfo.getProductUid(), null, ProductLogType.applyForRemoval.getKey(), "供应商申请下架商品", time));
                    productInfo.setSumbitStatus(productInfoEditVo.getSumbitStatus());
                    productInfo.setSubmitUid(userId);
                    productInfo.setSubmitName(username);
                    productInfo.setSubmitTime(time);
                }
            }
            String key = CachePrefix.API_PRODUCT_DETAIL + productInfo.getProductUid();
            if (DataStatus.valid.getKey().equals(productInfoEditVo.getDataStatus())) {
                iProductLogService.insertProductsLog(new ProductLog(productInfo.getProductUid(), null, ProductLogType.dataStatus.getKey(), "由下架改为上架", time));
                productInfo.setDataStatus(productInfoEditVo.getDataStatus());
                productInfo.setSumbitStatus(ProductSumbitStatus.normal.getKey());
                redisService.deleteObject(key);

                redisService.deleteObject(CachePrefix.TEMPLATE_PRODUCT + productInfo.getProductUid());
                iProductInfoGroupService.delRedisGroup(productInfo.getProductUid());
            }
            if (DataStatus.invalid.getKey().equals(productInfoEditVo.getDataStatus())) {
                iProductLogService.insertProductsLog(new ProductLog(productInfo.getProductUid(), null, ProductLogType.dataStatus.getKey(), "由上架改为下架", time));
                productInfo.setDataStatus(productInfoEditVo.getDataStatus());
                productInfo.setSumbitStatus(ProductSumbitStatus.normal.getKey());
                redisService.deleteObject(key);

                redisService.deleteObject(CachePrefix.TEMPLATE_PRODUCT + productInfo.getProductUid());
                iProductInfoGroupService.delRedisGroup(productInfo.getProductUid());
            }
            if (DataStatus.delete.getKey().equals(productInfoEditVo.getDataStatus())) {
                productInfo.setDataStatus(productInfoEditVo.getDataStatus());
            }
            productInfo.setUpdateTime(time);
            productInfo.setUpdateUid(userId);
            productInfo.setUpdateName(username);
            productInfoMapper.updateAndLog(productInfo);
            if (DataStatus.delete.getKey().equals(productInfoEditVo.getDataStatus())) {
                ProductSaveVo saveVo = new ProductSaveVo();
                saveVo.setUserUid(userId);
                saveVo.setUserName(username);
                saveVo.setTime(DateUtil.date());
                Long[] toBeStored = productUidS.toArray(new Long[productUidS.size()]);
                iProductPropertyValuesService.editProductSkuValues(saveVo, toBeStored); // 删除中间数据
                iProductSkuService.updateSkuStatus(saveVo, toBeStored); // 删除sku
                iProductInfoTagsService.updateInfoTagStatus(toBeStored);
            }
            redisService.deleteObject(CachePrefix.TEMPLATE_PRODUCT + productInfo.getProductUid());
        });
        return true;
    }


    @Override
    public List<HashMap> getGategoryProduct(Long categoryUid) {
        List<HashMap> hashMaps = new ArrayList<>();
        QueryWrapper<ProductInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("DATA_STATUS", DataStatus.valid.getKey());
        queryWrapper.eq("AUDIT_STATUS", DataStatus.valid.getKey());
        queryWrapper.eq("IS_CATEGORY_RECOMMEND", DataStatus.valid.getKey());
        queryWrapper.eq("CATEGORY_UID_ONE", categoryUid);
        List<ProductInfo> productInfos = productInfoMapper.selectList(queryWrapper);
        if (ObjectUtil.isEmpty(productInfos)) return hashMaps;
        productInfos.forEach(info -> {
            HashMap map = new HashMap();
            map.put("productUid", info.getProductUid());

            hashMaps.add(map);
        });
        return hashMaps;
    }

    private List<HashMap> setList(String name, String value, List<HashMap> list) {
        HashMap map = new HashMap();
        map.put("name", name);
        map.put("value", value);
        list.add(map);
        return list;
    }


    //产品分享背景图
    private final static String PRODUCT_BACKGROUND_URL = "http://resource.tkmall.tongkeer.com/product_share_bg.png";


    /**
     * 创建海报
     *
     * @param productUid
     * @param userId
     * @param token
     * @return
     */
    private BufferedImage createQrCode(Long productUid, Long userId, String token) {
        String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + token;
        Map<String, String> param = new HashMap<String, String>();
        param.put("scene", "proId=" + productUid + ";userId=" + userId);
        param.put("page", "pages/productDetail/productDetail");
        param.put("width", "112");
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        //InputStream is  = null;
        BufferedImage image = null;
        try {
            //创建Get请求，
            HttpPost httpGet = new HttpPost(url);
            StringEntity entity1 = new StringEntity(JSON.toJSONString(param), HTTP.UTF_8);
            entity1.setContentType("application/json");
            httpGet.setEntity(entity1);

            //执行Get请求，
            response = httpClient.execute(httpGet);
            //得到响应体
            HttpEntity entity = response.getEntity();
            //is = entity.getContent();
            image = ImageIO.read(entity.getContent());
            httpClient.close();
        } catch (IOException e) {
        }
        return image;
    }

    /**
     * 获取测试的分类
     *
     * @return
     */
    @Override
    public List<PddCategory> category() {
        List<PddCategory> list = redisService.getCacheList(CachePrefix.PDD_GATEGORY);
        if (ObjectUtil.isEmpty(list)) {
//            String clientId = "887de48e91664bc3bfc1cfd99b1b9c1f";
//            String clientSecret = "962dce278e96867d1b4402b0beb9da7aac7ad873";
//            PopClient client = new PopHttpClient(clientId, clientSecret);
//            PddGoodsCatsGetRequest request = new PddGoodsCatsGetRequest();
//            List<Long> as = new ArrayList<Long>();
//            as.add(0L);
//
//            request.setParentCatId(0L);
//            PddGoodsCatsGetResponse response = null;
//            try {
//                response = client.syncInvoke(request);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//            String transferToJson = JsonUtil.transferToJson(response);
//            JSONObject jobject = JSONObject.parseObject(transferToJson);
//            JSONObject jsonObject = jobject.getJSONObject("goods_cats_get_response");
//            JSONArray array = jsonObject.getJSONArray("goods_cats_list");
//            if (ObjectUtil.isNotEmpty(array)) {
//                list = JSONObject.parseArray(array.toJSONString(), PddCategory.class);
//            }
//            redisService.setCacheList(CachePrefix.PDD_GATEGORY, list);
        }
        return list;
    }

    @Override
    public Boolean goods(List<PddCategory> listCate) {
        Long userId = SecurityUtils.getUserId();
        String userName = SecurityUtils.getUsername();
        Long platformUid = SecurityUtils.getPlatformId();
        String clientId = "887de48e91664bc3bfc1cfd99b1b9c1f";
        String clientSecret = "962dce278e96867d1b4402b0beb9da7aac7ad873";
        //判断是否超过100条
        QueryWrapper<ProductInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("DATA_STATUS", DataStatus.delete.getKey());
        queryWrapper.eq("PLATFORM_UID", platformUid);
        queryWrapper.ne("PDD_UID", 0L);
        Integer integer = productInfoMapper.selectCount(queryWrapper);
        if (integer >= 100) throw new ProductException("测试数据已达到100条！");
        Integer number = 0;
        //HashMap testCategory = new HashMap();
        if (integer > 0) {// 说明已经添加过
            integer = 100 - integer;
            //testCategory = iProductCategoryService.getTestCategory();
            number = 1;
        }
        for (int i = 0; i < listCate.size(); i++) {
            PddCategory cate = listCate.get(i);
            // 先去添加分类,如果已添加,查询即可
//            ProductCategory category = new ProductCategory(cate, userId, userName, platformUid);
//            category = iProductCategoryService.insertProductCategoryPdd(category);
//            List<PddGoods> list = new ArrayList<>();
//            PopClient client = new PopHttpClient(clientId, clientSecret);
//            Long catId = cate.getCatId();
//            int totalPages = 0;//分页
//            PddDdkGoodsSearchRequest request = new PddDdkGoodsSearchRequest();
//            request.setPage(1);//默认值1，商品分页数
//            if (number == 0) {
//                request.setPageSize(20);//默认100，每页商品数量
//                request.setPage(1);//默认值1，商品分页数
//            } else {
//                if (integer == 0) continue;
//                if (integer - 20 > 0) {
//                    request.setPage(i + 2);//默认值1，商品分页数
//                    request.setPageSize(20);
//                    integer = integer - 20;
//                } else {
//                    request.setPage(i + 2);//默认值1，商品分页数
//                    request.setPageSize(integer);
//                    integer = 0;
//                }
//            }
//            request.setCatId(catId);
//            request.setWithCoupon(false);//是否只返回优惠券的商品，false返回所有商品，true只返回有优惠券的商品
//            request.setIsBrandGoods(false);//是否为品牌商品
//            PddDdkGoodsSearchResponse response = null;
//            try {
//                response = client.syncInvoke(request);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//            String result = JsonUtil.transferToJson(response);
//            JSONObject jobject = JSONObject.parseObject(result);
//            String listId = null;//翻页时必填前页返回的list_id值
//            Integer totalRows = 2;//返回商品总数
//            JSONObject goodsList = jobject.getJSONObject("goods_search_response");
//            if (goodsList != null) {
//                listId = goodsList.getString("list_id");//翻页时必填前页返回的list_id值
//                totalRows = goodsList.getInteger("total_count");//返回商品总数
//                JSONArray array = goodsList.getJSONArray("goods_list");
//                list = JSONObject.parseArray(array.toJSONString(), PddGoods.class);
//                pddSaveProductUid(list, userId, userName, platformUid, category.getCategoryUid());
//            }
        }

        return true;
    }

    /**
     * 增加测试商品
     *
     * @param list
     * @param userId
     * @param userName
     * @param platformUid
     * @param cateUid
     */
    private void pddSaveProductUid(List<PddGoods> list, Long userId, String userName, Long platformUid, Long cateUid) {
        list.forEach(goods -> {
            ProductInfo info = new ProductInfo(goods, userId, userName, platformUid, cateUid);
            this.save(info);
            ProductSaveVo productSaveVo = new ProductSaveVo();
            productSaveVo.setProductUid(info.getProductUid());
            productSaveVo.setPlatformUid(platformUid);
            //iProductCountService.insertProductCount(productSaveVo);// 初始化商品数据
        });
    }

    /**
     * 用于模板商品远程调用
     *
     * @param productUid
     * @return
     */
    public ProductInfoVo getTemplatePro(Long productUid) {
        String key = CachePrefix.TEMPLATE_PRODUCT + productUid;
        ProductInfoVo vo = redisService.get(key, ProductInfoVo.class);
        if (ObjectUtil.isEmpty(vo)) {
            vo = productInfoMapper.getTemplatePro(productUid);
            //查询商品标签
            vo.setTagsName(iProductTagsService.getTagsName(vo.getProductUid()));
            // 商品单位
            if (ObjectUtil.isNotEmpty(vo.getUnitUid())) {
                ProductUnit productUnit = iProductUnitService.selectProductUnitById(vo.getUnitUid());
                if (ObjectUtil.isNotEmpty(productUnit)) {
                    vo.setUnitName(productUnit.getUnitName());
                }
            }
            redisService.set(key, vo, 30L, TimeUnit.MINUTES);
        }


        return vo;
    }

    /**
     * 查询商品详情 api
     *
     * @param proUid
     * @return
     */
    @Override
    public ProductInfoVo getProductDetail(Long proUid) {
        ProductInfoVo rst = null;
        ProductInfo productInfo = getById(proUid);
        if (productInfo != null) {
            rst = new ProductInfoVo();
            BeanUtils.copyProperties(productInfo, rst);

            return rst;
        }
        return null;
    }

    /**
     * 查询sku详情 api
     *
     * @param skuId
     * @return
     */
    @Override
    public SkuApi getSkuDetail(Long skuId) {
        ProductSku sku = iProductSkuService.getById(skuId);
        if (sku != null) {
            SkuApi data = new SkuApi();
            BeanUtils.copyProperties(sku, data);
            return data;
        }
        return null;
    }
}
